/**
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the latest version of the GNU Lesser General
 * Public License as published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program (LICENSE.txt); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.lightframework.jamwiki.servlets;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jamwiki.DataHandler;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.WikiMessage;
import org.jamwiki.model.VirtualWiki;
import org.jamwiki.model.WikiUser;
import org.jamwiki.servlets.ServletUtil;
import org.jamwiki.servlets.ServletUtilEx;
import org.jamwiki.servlets.WikiPageInfo;
import org.jamwiki.utils.WikiUtil;
import org.lightframework.jamwiki.Version;
import org.lightframework.jamwiki.utils.WikiDatabaseEx;
import org.springframework.web.servlet.ModelAndView;

/**
 * servlet to initialze default config and topics after jamwiki setup successfully.
 *  
 * @author fenghm(live.fenghm@gmail.com)
 */
public class SetupServletEx extends org.jamwiki.servlets.SetupServlet {
	
	@Override
    protected ModelAndView handleJAMWikiRequest(HttpServletRequest request, HttpServletResponse response, ModelAndView next, WikiPageInfo pageInfo)
            throws Exception {
		boolean postback = null != request.getParameter("function");
		
		if(postback){
			//before postback to jamwiki's SetupServlet,set default properties
			setDefaultProperties(request);	
		}else{
			//set default user name and password before rendering the setup view
			next.addObject("username", "admin");
			next.addObject("newPassword", "admin");
			next.addObject("confirmPassword", "admin");
		}

		ModelAndView mv = super.handleJAMWikiRequest(new MockHttpRequest(request), response, next, pageInfo);
		
		if(postback && !WikiUtil.isFirstUse()){
			//setup successfully
			
			WikiUser user = getAdminUser(request);
			Locale locale = request.getLocale();
			
			//init default topics
			DataHandler handler = WikiBase.getDataHandler();
			for(VirtualWiki wiki : handler.getVirtualWikiList()){
				WikiDatabaseEx.setupDefaultPages(locale, wiki.getName(), user);
			}
			
			//create special wikis
			WikiDatabaseEx.createSpecialWikis(request, locale, user);
			
			//change pageinfo's virtual wiki to current wiki.
			pageInfo.setVirtualWikiName(Environment.getValue(Environment.PROP_VIRTUAL_WIKI_DEFAULT));
			WikiContext.setIfNotSet(request, mv, pageInfo);
		}
		
		pageInfo.setPageTitle(new WikiMessage("setup.title", Version.CURRENT));
		
		return mv;
    }
	
	protected void setDefaultProperties(HttpServletRequest request) throws IOException{
		String homeDir = request.getParameter(Environment.PROP_BASE_FILE_DIR);
		if(!StringUtils.isBlank(homeDir)){
			
			//TODO : hard code upload path
			String uploadDir  = homeDir.endsWith("/") || homeDir.endsWith("\\") ? homeDir + "upload" : homeDir + File.separator + "upload";
			String uploadPath = ServletUtilEx.getContextPath(request) + "/upload";
			
			//create upload dir
			File file = new File(uploadDir);
			if(!file.exists()){
				file.mkdirs();
			}
			
			request.setAttribute(Environment.PROP_FILE_DIR_FULL_PATH, uploadDir);
			request.setAttribute(Environment.PROP_FILE_DIR_RELATIVE_PATH, uploadPath);
			
			setProperty(request,Environment.PROP_SITE_NAME);
			setProperty(request,Environment.PROP_VIRTUAL_WIKI_DEFAULT);
		}
	}
	
	private void setProperty(HttpServletRequest request,String prop){
		Environment.setValue(prop, request.getParameter(prop));
	}
	
	protected WikiUser getAdminUser(HttpServletRequest request) throws Exception {
		String username = request.getParameter("username");
		WikiUser user = new WikiUser(username);
		user.setCreateIpAddress(ServletUtil.getIpAddress(request));
		user.setLastLoginIpAddress(ServletUtil.getIpAddress(request));
		return user;
	}	
	
	private static final class MockHttpRequest extends HttpServletRequestWrapper{

		public MockHttpRequest(HttpServletRequest request) {
			super(request);
        }

		@Override
        public String getParameter(String name) {
			if(Environment.PROP_FILE_DIR_FULL_PATH.equals(name)){
				return (String)getRequest().getAttribute(Environment.PROP_FILE_DIR_FULL_PATH);
			}else if(Environment.PROP_FILE_DIR_RELATIVE_PATH.equals(name)){
				return (String)getRequest().getAttribute(Environment.PROP_FILE_DIR_RELATIVE_PATH);
			}
		
			return super.getParameter(name);
		}
	}
}
